package service

import (
	"context"
	"encoding/json"
	"fmt"
	"jk-time/webook/Tag/domain"
	"jk-time/webook/Tag/repository"
	"jk-time/webook/pkg/logger"
	"jk-time/webook/tag/events"
	"time"
)

type TagService interface {
	CreateTag(ctx context.Context, uid int64, name string) (int64, error)
	AttachTags(ctx context.Context, uid int64, biz string, bizId int64, tags []int64) error
	GetTags(ctx context.Context, uid int64) ([]domain.Tag, error)
	GetBizTags(ctx context.Context, uid int64, biz string, bizId int64) ([]domain.Tag, error)
}

type tagService struct {
	repo     repository.TagRepository
	logger   logger.Logger
	producer events.Producer
}

func (svc *tagService) CreateTag(ctx context.Context, uid int64, name string) (int64, error) {
	return svc.repo.CreateTag(ctx, domain.Tag{
		Uid:  uid,
		Name: name,
	})
}
func (svc *tagService) GetTags(ctx context.Context, uid int64) ([]domain.Tag, error) {
	return svc.repo.GetTags(ctx, uid)
}
func (svc *tagService) GetBizTags(ctx context.Context, uid int64, biz string, bizId int64) ([]domain.Tag, error) {
	return svc.repo.GetBizTags(ctx, uid, biz, bizId)
}
func (svc *tagService) AttachTags(ctx context.Context, uid int64, biz string, bizId int64,
	tagIds []int64) error {
	err := svc.repo.BindTagToBiz(ctx, uid, biz, bizId, tagIds)
	if err != nil {
		return err
	}
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		tags, err := svc.repo.GetTagsById(ctx, tagIds)
		cancel()
		if err != nil {
			svc.logger.Error("通过id获取标签失败：", logger.Error(err))
			return
		}
		val, _ := json.Marshal(tags)
		ctx, cancel = context.WithTimeout(context.Background(), time.Second)
		err = svc.producer.ProduceSearchEvent(ctx, events.SyncDataEvent{
			IndexName: "tags_idx",
			DocID:     fmt.Sprintf("%d_%s_%d", uid, biz, bizId),
			Data:      string(val),
		})
		cancel()
		if err != nil {
			svc.logger.Error("标签发送kafka失败：", logger.Error(err))
		}
	}()
	return err
}
